package com.tengju.user.infrastructure.repository;

import com.tengju.user.domain.model.user.ManageUser;
import com.tengju.user.domain.model.user.ManageUserRepository;
import com.tengju.user.infrastructure.persistence.mybatis.dataobject.SysUserDO;
import com.tengju.user.infrastructure.persistence.mybatis.mapper.dealer.custom.SysUserDOCustomMapper;
import com.tengju.user.infrastructure.persistence.mybatis.mapper.dealer.generate.SysUserDOMapper;
import com.tengju.user.infrastructure.persistence.redis.RedisService;
import com.tengju.user.infrastructure.persistence.redis.dataobject.RedisKeyObject;
import com.tengju.user.infrastructure.persistence.redis.dataobject.RedisKeyPrefix;
import com.tengju.user.infrastructure.repository.convert.ManageUserConvert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Repository
public class ManageUserRepositoryImpl implements ManageUserRepository {


    @Resource
    SysUserDOCustomMapper sysUserDOCustomMapper;

    @Resource
    SysUserDOMapper sysUserDOMapper;

    @Autowired
    RedisService redisService;

    private final Integer MANAGE_USER_VALID_STATUS = 1;

    @Override
    public ManageUser selectByNameAndPwd(String username, String pwd) {
        pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
        SysUserDO sysUserDO = sysUserDOCustomMapper.selectByNameAndPwd(username,pwd);
        return ManageUserConvert.convertSysUserToEntity(sysUserDO);
    }

    @Override
    public void saveManageUserCache(String token, ManageUser manageUser, long loginTTL, TimeUnit hours) {
        RedisKeyObject redisKeyObject = new RedisKeyObject(RedisKeyPrefix.LOGIN_TOKEN, token);
        redisService.setValue(redisKeyObject, manageUser, loginTTL, TimeUnit.HOURS);
    }

    @Override
    public void deleteManageUserCache(String token) {
        RedisKeyObject RedisKeyObject = new RedisKeyObject(RedisKeyPrefix.LOGIN_TOKEN,token);
        redisService.delKey(RedisKeyObject);
    }

    @Override
    public void addManageUser(String userName, String pwd, String realName) {
        pwd = DigestUtils.md5DigestAsHex(pwd.getBytes());
        Date now = new Date();
        SysUserDO sysUserDO = new SysUserDO();
        sysUserDO.setRealName(realName);
        sysUserDO.setPassword(pwd);
        sysUserDO.setUsername(userName);
        sysUserDO.setValidStatus(MANAGE_USER_VALID_STATUS.byteValue());
        sysUserDO.setUpdateTime(now);
        sysUserDO.setCreateTime(now);
        sysUserDOMapper.insertSelective(sysUserDO);
    }
}
